using System;
using Curriculum.DataSet;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using E4RPDevExpress;

namespace Curriculum.Controls
{
    public partial class PositionXtraUserControl : XtraUserControl, IGridView, IList
    {
        private BackOfficeController _controller;

        #region Properties

        public BackOfficeController Controller
        {
            set
            {
                _controller = value;
                //SetGridDataSource();
                _controller.PositionSaved += delegate { SetGridDataSource(); };
            }
        }

        #endregion

        public PositionXtraUserControl()
        {
            InitializeComponent();
            gridView.DoubleClick += GridViewDoubleClick;
        }

        public void Reload()
        {
            SetGridDataSource();
        }

        #region Private Methods

        public string GetExtendedFilter()
        {
            if (ReferenceEquals(gridView.ActiveFilterCriteria, null))
                return "";
            return gridView.ActiveFilterCriteria.LegacyToString();
        }

        private void SetGridDataSource()
        {
            var dataSet = _controller.GetPositions(GetExtendedFilter());
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.Position.TableName;
        }

        private void ShowPosition(long documentId)
        {
            var window = new PositionXtraForm { DocumentId = documentId, Controller = _controller };
            window.ShowDialog();
        }

        #endregion

        #region IGridView

        public GridView GridView()
        {
            return gridView;
        }

        public string ListName
        {
            get { return "Position"; }
        }

        #endregion

        public void AddDocument()
        {
            ShowPosition(-1);
        }

        void GridViewDoubleClick(object sender, EventArgs e)
        {
            var position = (PositionDataSet.PositionRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (position == null)
                return;
            ShowPosition(position.Id);
        }        

    }
}
